package net.qqxh.resolve2view.impl;

import net.qqxh.common.utils.FileAnalysisTool;
import net.qqxh.common.utils.TxtCharsetUtil;
import net.qqxh.resolve2view.File2ViewResolve;
import org.apache.commons.io.FileUtils;
import org.jodconverter.DocumentConverter;
import org.jodconverter.office.OfficeException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author yudian-it
 */
@Component
public class Excel2ViewResolve implements File2ViewResolve {
    @Autowired
    private DocumentConverter documentConverter;
    private static String RESOLVE_LIST = ".xls|.xlsx";
    private static String RESOLVE2FIX = "html";


    /**
     * 转换office文档
     *
     * @param fromPath 源文件路径
     * @return toPath   view目标文件路径
     */
    @Override
    public String resolve(String fromPath,String toPath) throws OfficeException {
        File inputFile = new File(fromPath);
        File tofile = new File(toPath);
        if (inputFile.exists()) {
            try {
                documentConverter.convert(inputFile).to(tofile).execute();
                changeHtmlImgUrl(toPath);
            } catch (OfficeException e) {
                e.printStackTrace();
                toPath = null;
                throw e;
            }
        }
        return toPath;
    }

    private void changeHtmlImgUrl(String htmlPath) {
        try {
            File htmlfile=  new File(htmlPath);
            String encoding = FileAnalysisTool.guessFileEncoding(htmlfile);
            Document doc =Jsoup.parse(htmlfile ,encoding);
            Elements imgs = doc.select("img");
            for (Element img : imgs) {
                String linkHref = img.attr("src");
                String ppath = htmlfile.getParent();
                img.attr("src", "/loadImg?path="+ URLEncoder.encode(ppath+File.separator,"utf-8")+linkHref);
            }
            FileUtils.writeStringToFile(htmlfile,doc.html(),encoding);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public boolean canResolve(String fileFix) {
        return RESOLVE_LIST.contains(fileFix.toLowerCase());
    }

    @Override
    public String getviewFix() {
        return RESOLVE2FIX;
    }
}
